package DGWeb.Servlets;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.SingleThreadModel;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.tomcat.dbcp.dbcp.BasicDataSource;

import DGWeb.AppConstants;

/**
 * Servlet implementation class FollowUser
 */
@WebServlet("/FollowUser")
public class FollowUser extends HttpServlet implements SingleThreadModel {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FollowUser() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		HttpSession UserSession = request.getSession();
		String user = (String) UserSession.getAttribute("Username");
		try 
		{
			// extract data from Json
			InputStreamReader isr = new InputStreamReader(request.getInputStream());
			BufferedReader br = new BufferedReader(isr);
			StringBuilder jsonFileContent = new StringBuilder();
			//read the only line
			jsonFileContent.append( br.readLine());
			String[] DataArray = jsonFileContent.toString().split(":");
			String[] Dt = AppConstants.FOLLOWER_INSERT.split("//");
			String exec = Dt[0] + user + Dt[1]+ DataArray[1].substring(1, DataArray[1].length()-2 ) + Dt[2]; 
			
			Context context = new InitialContext();
			BasicDataSource ds = (BasicDataSource)context.lookup(AppConstants.DB_DATASOURCE);
			Connection conn = ds.getConnection();
			//create statement
			Statement stmt = conn.createStatement();
			//for insert
			stmt.executeUpdate(exec);

			//commit update
    		conn.commit();
    		stmt.close();
    		conn.close();
    		
			
		}catch (NamingException |SQLException e){
			
			e.printStackTrace();
		}
		
		
	}

}
